package org.xw.service.impl;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.xw.dto.*;
import org.xw.mapper.ChatMapper;
import org.xw.mapper.MessageMapper;
import org.xw.mapper.UserMapper;
import org.xw.pojo.*;
import org.xw.service.ChatService;
import org.xw.utils.JWTUtil;
import org.xw.utils.QwenUtil;
import org.xw.utils.ResponseUtil;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {
    @Resource
    ChatMapper chatMapper;

    @Resource
    MessageMapper messageMapper;

    @Resource
    UserMapper userMapper;

    /**
     * 创建群聊
     *
     * @param httpServletRequest
     * @param chat
     * @return
     */
    @Override
    public ResponseUtil create(HttpServletRequest httpServletRequest,@RequestBody ChatPojo chat) {
        System.out.println(chat);
        chatMapper.create(chat);

        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        if (chat.getMembersPojoList().size() >= 2) {
            //添加多人标志，群聊图片，群聊名称
            chatMapper.addMulti(chat.getId(), chat.getHeadImage(), chat.getChatName());

            if (userId != null) {
                chatMapper.addLeader(Integer.parseInt(userId), chat.getId());
            }
        } else {
            if (userId != null) {
                chatMapper.addMember(Integer.parseInt(userId), chat.getId());
            }
        }
        for (MembersPojo membersPojo : chat.getMembersPojoList()) {
            chatMapper.addMember(membersPojo.getUserId(), chat.getId());
        }

        ChatPojo chatPojo = chatMapper.getChatById(chat.getId());
        chatPojo.setMembersPojoList(chatMapper.getMembers(chat.getId()));
        return ResponseUtil.success(chatPojo);
    }

    /**
     * 加人
     *
     * @param httpServletRequest
     * @param membersPojos
     * @return
     */
    @Override
    public ResponseUtil Pull(HttpServletRequest httpServletRequest, List<MembersPojo> membersPojos) {
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        for (MembersPojo membersPojo : membersPojos) {
            chatMapper.addMember(membersPojo.getUserId(), membersPojo.getChatId());
        }
        PullToChatDTO pullToChatDTO = new PullToChatDTO();
        if (userId != null) {
            pullToChatDTO.setUserId(Integer.valueOf(userId));
        }
        pullToChatDTO.setUpdateTime(chatMapper.getUpdateTime(membersPojos.get(0).getChatId()));
        pullToChatDTO.setMembersPojoList(membersPojos);
        return ResponseUtil.success(pullToChatDTO);
    }

    /**
     * 查询群聊信息
     *
     * @return
     */
    @Override
    public ResponseUtil getChatById(HttpServletRequest httpServletRequest, Integer chatId) {
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        ChatPojo chat = chatMapper.getChatById(chatId);
        ChatDTO chatDTO = new ChatDTO();
        chatDTO.setChatName(chat.getChatName());
        chatDTO.setHeadImage(chat.getHeadImage());
        chatDTO.setUpdateTime(chat.getUpdateTime());
        chatDTO.setStatus(chat.getStatus());
        List<ChatOneDTO> chatOneDTOS = chatMapper.getPerson(chatId);
//        for (ChatOneDTO chatOneDTO : chatOneDTOS) {
//            chatOneDTO.setRemark(chatMapper.getRemarkByUserId(Integer.valueOf(userId),chatOneDTO.getUserId()));
//        }
        chatDTO.setChatOneDTOS(chatOneDTOS);
        MembersPojo membersPojo = chatMapper.getMember(userId, chatId);
        chatDTO.setTop(membersPojo.getTop());
        chatDTO.setUserStatus(membersPojo.getStatus());
        return ResponseUtil.success(chatDTO);
    }

    /**
     * 踢人
     *
     * @param httpServletRequest 用户token
     * @param membersPojos
     * @return
     */
    @Override
    public ResponseUtil out(HttpServletRequest httpServletRequest,@RequestBody List<MembersPojo> membersPojos) {
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        int chatId = membersPojos.get(1).getChatId();
        if (chatMapper.getMember(userId, chatId).getStatus() == 1) {
            for (MembersPojo pojo : membersPojos) {
                chatMapper.out(pojo.getChatId(), pojo.getUserId());
            }
            return ResponseUtil.success(null);
        }
        return ResponseUtil.error("服务器错误");
    }

    /**
     * 解散群聊
     *
     * @param httpServletRequest
     * @param chatId
     * @return
     */
    @Override
    public ResponseUtil dissolve(HttpServletRequest httpServletRequest, Integer chatId) {
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        if (chatMapper.getMember(userId, chatId).getStatus() == 1) {
            chatMapper.dissolve(chatId);
            return ResponseUtil.success(null);
        }
        return ResponseUtil.error("网络错误");
    }

    /**
     * 退群
     *
     * @param httpServletRequest
     * @param chatId
     * @return
     */
    @Override
    public ResponseUtil quit(HttpServletRequest httpServletRequest, Integer chatId) {
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        if (chatMapper.getMember(userId, chatId).getStatus() == 1) {
            return ResponseUtil.error("确认要解散群聊吗");
        }
        int i = chatMapper.out(Integer.parseInt(userId), chatId);
        if (i == 0) {
            return ResponseUtil.error("网络错误");
        }
        return ResponseUtil.success(null);
    }

    /**
     * 置顶群聊
     *
     * @param httpServletRequest
     * @param chatId
     * @return
     */
    @Override
    public ResponseUtil top(HttpServletRequest httpServletRequest, Integer chatId) {
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        int i = chatMapper.top(userId, chatId);
        if (i == 1) {
            return ResponseUtil.success(null);
        }
        return ResponseUtil.error("网络错误");
    }

    /**
     * 更新昵称、图片
     *
     * @param httpServletRequest
     * @param chatPojo
     * @return
     */
    @Override
    public ResponseUtil update(HttpServletRequest httpServletRequest,@RequestBody ChatPojo chatPojo) {
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        if (chatMapper.getMember(userId, chatPojo.getId()) != null) {
            int i = chatMapper.updateData(chatPojo);
            if (i == 1) {
                return ResponseUtil.success(chatMapper.getChatById(chatPojo.getId()));
            }
            return ResponseUtil.error("网络错误");
        }
        return ResponseUtil.error("你不是群成员");
    }

    @Override
    public List<Integer> getUserIds(int chatId) {
        return chatMapper.getUserIds(chatId);
    }

    /**
     * 通义千问聊天方法
     *
     * @param userId
     * @param msg
     * @return
     * @throws NoApiKeyException
     * @throws InputRequiredException
     */
    @Override
    public ResponseUtil qw(@RequestParam String userId,@RequestParam String msg) throws NoApiKeyException, InputRequiredException {
        //判断userId
        if (userId != null) {
            //判断是否有发过信息,没有会创建
            QwChat qwChat = createQW(userId);
            QwRecord qwRecord = new QwRecord();
            qwRecord.setRecord(msg);
            qwRecord.setUserId(Integer.parseInt(userId));
            qwRecord.setQwenId(qwChat.getId());
            //判断添加消息
            if (messageMapper.insQw(qwRecord) >= 0) {
                //这里发消息给千问
                GenerationResult result = QwenUtil.callWithMessage(msg);
                //保存消息到数据库
                if (result != null) {
                    qwRecord.setUserId(0);
                    qwRecord.setRecord(result.getOutput().getChoices().get(0).getMessage().getContent());
                    messageMapper.insQw(qwRecord);
                    return ResponseUtil.success(qwRecord);
                }
                return null;
            } else {
                return ResponseUtil.error("用户消息储存失败");
            }
        }
        return ResponseUtil.error("无用户认证");
    }

    /**
     * 查询个人所有群聊
     * @param httpServletRequest
     * @return
     */
    @Override
    public ResponseUtil getChatList(HttpServletRequest httpServletRequest) {
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        List<Integer> chatIds = chatMapper.getChatList(Integer.parseInt(userId));
        List<ChatDTO> chatDTOS = new ArrayList<>();
        ChatDTO qwDTO = chatMapper.getQW(Integer.valueOf(userId));
        if (qwDTO == null) {

            System.out.println("无千问聊天id,创建new聊天");
            ChatDTO newQwDTO = new ChatDTO();
            QwChat qwChat =new QwChat();
            qwChat.setUserId(Integer.parseInt(userId));
            chatMapper.insQW(qwChat);
            newQwDTO.setId(qwChat.getId());
            newQwDTO.setStatus(1);
            MessagePojo messagePojo = new MessagePojo();
            messagePojo.setChatId(newQwDTO.getId());
            messagePojo.setRecord("你好！很高兴能为你服务。有什么我可以帮你的吗？");
            chatMapper.newQwMsg(messagePojo);

        }else {

            qwDTO.setIsQw(1);
            ChatOneDTO chatOneDTO = new ChatOneDTO(0,"通义千问",null,"http://93ex15636hn2.vicp.fun/image/ty.png");
            List<ChatOneDTO> qw =new ArrayList<>();

            //填入user和通义信息
            qw.add(chatMapper.getNameAndImg(Integer.parseInt(userId)));
            qw.add(chatOneDTO);
            qwDTO.setChatOneDTOS(qw);
            qwDTO.setUsername(chatOneDTO.getUsername());
            qwDTO.setUserImage(chatOneDTO.getHeadImage());
            MessagePojo messagePojo = chatMapper.getQwNewMsg(qwDTO.getId());
            qwDTO.setNewMsg(messagePojo);
            qwDTO.setStatus(1);
            chatDTOS.add(qwDTO);

        }
        for (Integer chatId : chatIds) {
            ChatPojo chat = chatMapper.getChatById(chatId);
            ChatDTO chatDTO = new ChatDTO();
            chatDTO.setId(chatId);
            chatDTO.setChatName(chat.getChatName());
            chatDTO.setHeadImage(chat.getHeadImage());
            chatDTO.setUpdateTime(chat.getUpdateTime());
            chatDTO.setStatus(chat.getStatus());
//            List<Integer> userIds = chatMapper.getUserIds(chatId);
            List<ChatOneDTO> chatOneDTOS = chatMapper.getPerson(chatId);
//            for (ChatOneDTO chatOneDTO : chatOneDTOS) {
//                chatOneDTO.setRemark(chatMapper.getRemarkByUserId(Integer.valueOf(userId),chatOneDTO.getUserId()));
//            }
            chatDTO.setChatOneDTOS(chatOneDTOS);
            MembersPojo membersPojo = chatMapper.getMember(userId, chatId);
            chatDTO.setTop(membersPojo.getTop());
            chatDTO.setUserStatus(membersPojo.getStatus());
            chatDTO.setNewMsg(chatMapper.getNewMsg(chatId));


            if (chatOneDTOS.size() == 2) {
                //单聊则填入对方信息
                for (ChatOneDTO chatOneDTO : chatOneDTOS) {
                    if (!Integer.valueOf(userId).equals(chatOneDTO.getUserId())) {
                        UserPojo userPojo = userMapper.selNameImage(chatOneDTO.getUserId());
                        chatDTO.setUsername(userPojo.getUsername());
                        chatDTO.setUserImage(userPojo.getHeadImage());
                    }
                }

            }

            chatDTOS.add(chatDTO);
        }
        return ResponseUtil.success(chatDTOS);
    }
//
//
//}

    /**
     * 通义千问聊天创建
     */
    public QwChat createQW(String userId) {
        QwChat qwChat = chatMapper.selQW(Integer.valueOf(userId));
        if (qwChat != null) {
            return qwChat;
        } else {
            QwChat qwChat1 = new QwChat();
            qwChat1.setUserId(Integer.parseInt(userId));
            chatMapper.insQW(qwChat1);
            return qwChat1;
        }
    }


}
